package domain;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class DAOPhoneNumber extends HibernateDaoSupport implements IDAOPhoneNumber {

	@Override
	public Boolean addPhoneToContact(final long contactId, final String phoneKind, final String phoneNumber ) {
		return (Boolean)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws
			HibernateException{
				PhoneNumber pn = new PhoneNumber(phoneKind, phoneNumber);
				Contact c = (Contact) session.get(Contact.class, contactId);
				c.addPhone(pn);
				
				session.saveOrUpdate(c);
				return true;
			}
		});
		
	}

	@Override
	public Boolean modifyPhoneNumber(final long phoneId, final String phoneKind, final String phoneNumber) {
		return (Boolean)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws
			HibernateException{
				PhoneNumber pn = (PhoneNumber) session.get(PhoneNumber.class, phoneId);
				pn.setPhoneKind(phoneKind);
				pn.setPhoneNumber(phoneNumber);
				
				session.saveOrUpdate(pn);
				return true;
			}
		});
	}

	@Override
	public PhoneNumber getPhoneNumber(final long phoneId) {
		return (PhoneNumber)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws
			HibernateException{
				PhoneNumber pn = (PhoneNumber) session.get(PhoneNumber.class, phoneId);
				return pn;
			}
		});
	}

	@Override
	public boolean deletePhoneNumber(final long phoneId) {
		return (Boolean)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws
			HibernateException{
				PhoneNumber pn = (PhoneNumber) session.get(PhoneNumber.class, phoneId);
				Contact contact =pn.getContact();
				contact.removePhone(pn);
				session.saveOrUpdate(contact);
				session.delete(pn);
				return true;
			}
		});
	}
	
	

}
